package com.nutransit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.mylibrary.mylibrary.parsing.AsyncTaskInterface;
import com.mylibrary.mylibrary.parsing.AsyncTaskUtility;
import com.mylibrary.mylibrary.util.CommonCode;
import com.nutransit.commoncode.Webservice_parametrs;
import com.nutransit.map.DirectionsJSONParser;

public class Fragment_Cab_Driver_Detail extends Fragment implements Webservice_parametrs
{
	private View rootview;
	private TextView tv_Source, tv_Destination;
	public static View view;
	private GoogleMap map;

	private Context context;

	private ArrayList<LatLng> markerPoints;
	private String strSource, strDestination, strSource_lat, strSource_lon,
			strDestination_lat, strDestination_lon;
	public static int flag = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		if (flag == 0)
		{
			rootview = inflater.inflate(R.layout.fragment_cab_driver_details, container, false);
			view = rootview;
			flag = 1;
		}
		else
		{
			rootview = view;
		}
		init_var();

		return rootview;
	}

	private void init_var()
	{
		context = getActivity();

		tv_Source = (TextView) rootview.findViewById(R.id.tv_Source);
		tv_Destination = (TextView) rootview.findViewById(R.id.tv_Destination);
		if (getArguments().containsKey(TAG_data))
		{
			// String str_vanrouteimgurl =
			// getArguments().getString(TAG_vanimageURL);
			// JSONObject jsonObject = new
			// JSONObject(getArguments().getString(TAG_data));
			strSource = getArguments().getString(TAG_source);
			strDestination = getArguments().getString(TAG_destination);
			strSource_lat = getArguments().getString(TAG_lat_source);
			strSource_lon = getArguments().getString(TAG_long_source);
			strDestination_lat = getArguments().getString(TAG_lat_destination);
			strDestination_lon = getArguments().getString(TAG_long_destination);
		}
		tv_Source.setText(strSource + "");
		tv_Destination.setText(strDestination + "");

		markerPoints = new ArrayList<LatLng>();
		markerPoints.add(new LatLng(Double.parseDouble(strSource_lat), Double.parseDouble(strSource_lon)));
		markerPoints.add(new LatLng(Double.parseDouble(strDestination_lat), Double.parseDouble(strDestination_lon)));

		// http://nutransit.net/mobile/getcurrentlocation.php?userid=35&driverid=27
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put(TAG_userid, "35");
		hashMap.put(TAG_driverid, "27");
		new AsyncTaskUtility(context, hashMap, URL_CURRENT_LOCATION_CAB_USER).getJSONResponse(new AsyncTaskInterface()
		{
			@Override
			public void getJSONObjectFromAsynkTask(JSONObject json)
			{
				try
				{
					if (json != null)
					{
						if (json.has(TAG_message))
							CommonCode.showMessage(json.getString(TAG_message), context);
						if (json.has(TAG_status) && json.getString(TAG_status).equalsIgnoreCase(SUCCESS))
						{

						}
					}
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		});

		// for (int i = 0; i < lat.length; i++)
		// {
		// markerPoints.add(new LatLng(lat[i], lon[i]));
		// }

		// Getting reference to SupportMapFragment of the activity_main
		SupportMapFragment fm = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);

		// Getting Map for the SupportMapFragment
		map = fm.getMap();

		// Enable MyLocation Button in the Map
		map.setMyLocationEnabled(true);
		float zoom = map.getMaxZoomLevel();
		map.addMarker(new MarkerOptions().position(markerPoints.get(0)).draggable(false).title("").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker_1)));
		map.addMarker(new MarkerOptions().position(markerPoints.get(1)).draggable(false).title("").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker_1_red)));
		map.moveCamera(CameraUpdateFactory.newLatLng(markerPoints.get(0)));
		map.animateCamera(CameraUpdateFactory.newLatLngZoom(markerPoints.get(0), zoom - 6));

		LatLng origin = markerPoints.get(0);
		LatLng dest = markerPoints.get(1);

		// Getting URL to the Google Directions API
		String url = getDirectionsUrl(origin, dest);

		DownloadTask downloadTask = new DownloadTask();

		// Start downloading json data from Google Directions API
		downloadTask.execute(url);
	}

	private String getDirectionsUrl(LatLng origin, LatLng dest)
	{

		// Origin of route
		String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

		// Destination of route
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

		// Sensor enabled
		String sensor = "sensor=false";

		// Waypoints
		String waypoints = "";
		for (int i = 2; i < markerPoints.size(); i++)
		{
			LatLng point = (LatLng) markerPoints.get(i);
			if (i == 2)
				waypoints = "waypoints=";
			waypoints += point.latitude + "," + point.longitude + "|";
		}

		// Building the parameters to the web service
		String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + waypoints;

		// Output format
		String output = "json";

		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

		return url;
	}

	/** A method to download json data from url */
	private String downloadUrl(String strUrl) throws IOException
	{
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;
		try
		{
			URL url = new URL(strUrl);

			// Creating an http connection to communicate with url
			urlConnection = (HttpURLConnection) url.openConnection();

			// Connecting to url
			urlConnection.connect();

			// Reading data from url
			iStream = urlConnection.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

			StringBuffer sb = new StringBuffer();

			String line = "";
			while ((line = br.readLine()) != null)
			{
				sb.append(line);
			}

			data = sb.toString();

			br.close();

		}
		catch (Exception e)
		{
			Log.d("Exception while downloading url", e.toString());
		}
		finally
		{
			iStream.close();
			urlConnection.disconnect();
		}
		return data;
	}

	// Fetches data from url passed
	private class DownloadTask extends AsyncTask<String, Void, String>
	{

		// Downloading data in non-ui thread
		@Override
		protected String doInBackground(String... url)
		{

			// For storing data from web service
			String data = "";

			try
			{
				// Fetching the data from web service
				data = downloadUrl(url[0]);
			}
			catch (Exception e)
			{
				Log.d("Background Task", e.toString());
			}
			return data;
		}

		// Executes in UI thread, after the execution of
		// doInBackground()
		@Override
		protected void onPostExecute(String result)
		{
			super.onPostExecute(result);

			ParserTask parserTask = new ParserTask();

			// Invokes the thread for parsing the JSON data
			parserTask.execute(result);

		}
	}

	/** A class to parse the Google Places in JSON format */
	private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>>
	{

		// Parsing the data in non-ui thread
		@Override
		protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
		{

			JSONObject jObject;
			List<List<HashMap<String, String>>> routes = null;

			try
			{
				jObject = new JSONObject(jsonData[0]);
				DirectionsJSONParser parser = new DirectionsJSONParser();

				// Starts parsing data
				routes = parser.parse(jObject);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return routes;
		}

		// Executes in UI thread, after the parsing process
		@Override
		protected void onPostExecute(List<List<HashMap<String, String>>> result)
		{

			ArrayList<LatLng> points = null;
			PolylineOptions lineOptions = null;
			String distance = "", duration = "";
			System.out.println("Result of parsing :" + result);

			// Traversing through all the routes
			for (int i = 0; i < result.size(); i++)
			{
				points = new ArrayList<LatLng>();
				lineOptions = new PolylineOptions();

				// Fetching i-th route
				List<HashMap<String, String>> path = result.get(i);

				// Fetching all the points in i-th route
				for (int j = 0; j < path.size(); j++)
				{
					HashMap<String, String> point = path.get(j);
					if (j == 0)
					{ // Get distance from the list
						distance = (String) point.get("distance");
						continue;
					}
					else if (j == 1)
					{ // Get duration from the list
						duration = (String) point.get("duration");
						continue;
					}

					double lat = Double.parseDouble(point.get("lat"));
					double lng = Double.parseDouble(point.get("lng"));
					LatLng position = new LatLng(lat, lng);
					points.add(position);
				}
				distance = distance.replaceAll(" km", "");
				double distance_calculate = (Double.parseDouble(distance) * 0.621371);
				System.out.println("Distance location : " + distance_calculate);
				// Adding all the points in the route to LineOptions
				lineOptions.addAll(points);
				lineOptions.width(2);
				lineOptions.color(Color.RED);
			}

			// Drawing polyline in the Google Map for the i-th route
			map.addPolyline(lineOptions);
		}
	}
}